package com.dy.nygl.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dy.nygl.pojo.Device;
import com.dy.nygl.pojo.DeviceLog;
import com.dy.nygl.service.BuildingService;
import com.dy.nygl.service.DepartmentService;
import com.dy.nygl.service.DeviceLogService;
import com.dy.nygl.service.DeviceService;
import com.dy.nygl.service.RegionService;
import com.dy.nygl.service.RoomService;

@Controller
@RequestMapping("/device")
public class DeviceController {

	@Resource(name="deviceService")
	private DeviceService deviceService;
	@Resource(name="departmentService")
	private DepartmentService departmentService;
	@Resource(name="regionService")
	private RegionService regionService;
	@Resource(name="buildingService")
	private BuildingService buildingServie;
	@Resource(name="roomService") 
	private RoomService roomService;
	@Resource(name="deviceLogService")
	private DeviceLogService deviceLogService;
	
	@RequestMapping("/getDevice.action")
	public String getDevice(HttpServletRequest request,HttpServletResponse response) {
		int currPage = 1;
		int rowsPage = 10;
		int totalRows=deviceService.getDeviceCount(); //总行数
		
		int totalPage=totalRows/rowsPage;//总页数
		totalPage=(totalRows%rowsPage)>0?totalPage+1:totalPage;
		
		if (request.getParameter("currPage")!=null) {
			try { 
				currPage=Integer.parseInt(request.getParameter("currPage"));//当前显示第几页
				if(currPage < 1) {
					currPage = 1;
				} else if(currPage > totalPage) {
					currPage = totalPage;
				}
			} catch(Exception e) { 
				currPage=1;//当前显示第几页
			}
		} else {
			currPage=1;//当前显示第几页
		}		
		
		int begin=(currPage-1)*rowsPage;//计算分页开始行
		int end=currPage*rowsPage;
		
		List<Device> devicelist= deviceService.getDevice(begin, end); 
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			for(int i=0; i<devicelist.size(); i++) {
				Map<String, Object> map = new LinkedHashMap <String, Object>();
				map.put("id", devicelist.get(i).getId());
				map.put("name", devicelist.get(i).getName());
				map.put("number", devicelist.get(i).getNumber());
				map.put("model", devicelist.get(i).getModel());
				map.put("power",devicelist.get(i).getPower());
				map.put("voltage",devicelist.get(i).getVoltage());
				map.put("current",devicelist.get(i).getCurrent());
				map.put("devicedate",devicelist.get(i).getDevicedate());
				if(devicelist.get(i).getStatus() == 0) {
					map.put("status","正常");
				} else if(devicelist.get(i).getStatus() == 1) {
					map.put("status","关闭");
				} else {
					map.put("status","故障");
				}			
				list.add(map);					
			}	
		} catch(Exception e) {
			list = null;
		}
		
		request.setAttribute("currPage", currPage);
		request.setAttribute("rowsPage", rowsPage);
		request.setAttribute("totalRows", totalRows);
		request.setAttribute("totalPage", totalPage);
		request.setAttribute("list", list);
			
		return "forward:/jsp/device/device.jsp";
	}
	
	@RequestMapping("/addDevice")
	public String addDevice(HttpServletRequest request) {
		int departid = Integer.parseInt(request.getParameter("department"));
		int regionid = Integer.parseInt(request.getParameter("region"));
		int buildid = Integer.parseInt(request.getParameter("building"));
		int roomid = Integer.parseInt(request.getParameter("room"));
		String number = request.getParameter("number");
		
		String name = request.getParameter("name");
		String str = "";
		str += regionService.getRegionById(regionid).getName() + "_";
		str += buildingServie.getBuildingById(buildid).getName() + "_";
		str += roomService.getRoomById(roomid).getName() + "_";
		name = str + name;
		
		String model = request.getParameter("model");
		double power = Double.parseDouble(request.getParameter("power"));
		double voltage = Double.parseDouble(request.getParameter("voltage"));
		double current = Double.parseDouble(request.getParameter("current"));
		String devicedate = request.getParameter("devicedate");
		String environment = request.getParameter("environment");
		
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(date);
		
		Device device = new Device();		
		device.setName(name);
		device.setNumber(number);
		device.setDepartmentId(departid);
		device.setRoomId(roomid);
		device.setModel(model);
		device.setPower(power);
		device.setVoltage(voltage);
		device.setCurrent(current);
		device.setDevicedate(devicedate);
		device.setEnvironment(environment);
		device.setStatus(1);
		device.setCreatetime(time);
		
		deviceService.adDevice(device);
		
		return "redirect:getDevice.action";
	}
	
	@RequestMapping("/getDeviceById")
	@ResponseBody
	public Map<String,Object> getDeviceById(HttpServletRequest request) throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		
		Device device = deviceService.getDeviceById(id);
		
		Map<String, Object> map = new LinkedHashMap <String, Object>();
		
		int buildingId = roomService.getRoomById(device.getRoomId()).getBuildingId();		
		int regionId = buildingServie.getBuildingById(buildingId).getRegionId();
		String[] name = device.getName().split("_");
		map.put("departmentId", device.getDepartmentId());
		map.put("roomId", device.getRoomId());
		map.put("buildingId", buildingId);
		map.put("regionId", regionId);
		map.put("name", name[3]);
		map.put("number", device.getNumber());
		map.put("model", device.getModel());
		map.put("power", device.getPower());
		map.put("voltage", device.getVoltage());
		map.put("current", device.getCurrent());
		map.put("devicedate", device.getDevicedate());	
		map.put("environment", device.getEnvironment());
		map.put("status", device.getStatus());
		return map;
	}
	
	@RequestMapping("/updateDevice")
	public String updateDevice(HttpServletRequest request) throws Exception {
		int id = Integer.parseInt(request.getParameter("id"));
		int departid = Integer.parseInt(request.getParameter("department"));
		int regionid = Integer.parseInt(request.getParameter("region"));
		int buildid = Integer.parseInt(request.getParameter("building"));
		int roomid = Integer.parseInt(request.getParameter("room"));
		String number = request.getParameter("number");
		
		String name = request.getParameter("name");
		String str = "";
		str += regionService.getRegionById(regionid).getName() + "_";
		str += buildingServie.getBuildingById(buildid).getName() + "_";
		str += roomService.getRoomById(roomid).getName() + "_";
		name = str + name;
		
		
		String model = request.getParameter("model");
		double power = Double.parseDouble(request.getParameter("power"));
		double voltage = Double.parseDouble(request.getParameter("voltage"));
		double current = Double.parseDouble(request.getParameter("current"));
		String devicedate = request.getParameter("devicedate");
		String environment = request.getParameter("environment");
		int currentStatus = Integer.parseInt(request.getParameter("status"));
		
		Device device = deviceService.getDeviceById(id);
		int pastStatus = device.getStatus();
		
		device.setName(name);
		device.setNumber(number);
		device.setDepartmentId(departid);
		device.setRoomId(roomid);
		device.setModel(model);
		device.setPower(power);
		device.setVoltage(voltage);
		device.setCurrent(current);
		device.setDevicedate(devicedate);
		device.setEnvironment(environment);
		device.setStatus(currentStatus);
		deviceService.updateDevice(device);
		
		//设备管理中对设备的状态进行改变，设备日志表进行相关操作
		if(currentStatus != pastStatus) {
			
			if(pastStatus == 0 || pastStatus == 2) {
				DeviceLog dl = deviceLogService.getDeviceLogByMaxAndId(id);					
				if(dl != null) {
					dl.setEndtime(new Timestamp(new Date().getTime()));	
					deviceLogService.updateDeviceLog(dl);			
				}				
			}
			
			if(currentStatus == 0) {
				DeviceLog dl = new DeviceLog();
				dl.setDeviceId(id);
				dl.setStatus(0);
				dl.setStarttime(new Timestamp(new Date().getTime()));
				dl.setEndtime(new Timestamp(new Date().getTime()));
				deviceLogService.addDeviceLog(dl);
			} else if(currentStatus == 2) {
				DeviceLog dl = new DeviceLog();
				dl.setDeviceId(id);
				dl.setStatus(1);
				dl.setStarttime(new Timestamp(new Date().getTime()));
				dl.setEndtime(new Timestamp(new Date().getTime()));
				deviceLogService.addDeviceLog(dl);
			}
		}
		
		return "redirect:getDevice.action";
	}
	
	@RequestMapping("/deleteDevice.action")
	public String deleteDevice(HttpServletRequest request) {
		int id = Integer.parseInt(request.getParameter("id"));
		deviceService.deleteDevice(id);
		return "redirect:getDevice.action";
	}
	
}
